# 阿里云ECS SSH连接脚本
# 使用方法: 
#   .\connect_aliyun.ps1 -IP "你的IP" -Key "密钥路径"
#   或
#   .\connect_aliyun.ps1 -Config "aliyun-ecs"

param(
    [string]$IP,
    [string]$Port = "22",
    [string]$User = "root",
    [string]$Key,
    [string]$Config,
    [switch]$Upload,
    [switch]$Download,
    [string]$File,
    [string]$RemotePath
)

# 如果指定了配置文件名称
if ($Config) {
    Write-Host "🚀 使用配置文件连接: $Config" -ForegroundColor Cyan
    $result = ssh -T $Config 2>&1
    if ($LASTEXITCODE -eq 0) {
        Write-Host "✅ 连接测试成功！" -ForegroundColor Green
        ssh $Config
    } else {
        Write-Host "❌ 连接失败，请检查配置" -ForegroundColor Red
        Write-Host $result
    }
    return
}

# 如果没有IP则提示
if (-not $IP) {
    Write-Host "❌ 错误: 请提供IP地址" -ForegroundColor Red
    Write-Host "用法: .\connect_aliyun.ps1 -IP 'xxx.xxx.xxx.xxx' [-Key 'path/to/key.pem']" -ForegroundColor Yellow
    return
}

Write-Host "🚀 连接到阿里云实例..." -ForegroundColor Cyan
Write-Host "IP: $IP" -ForegroundColor Green
Write-Host "端口: $Port" -ForegroundColor Green
Write-Host "用户: $User" -ForegroundColor Green

# 构建SSH命令
if ($Key) {
    if (Test-Path $Key) {
        Write-Host "🔑 使用密钥文件: $Key" -ForegroundColor Yellow
        $sshCommand = "ssh -i `"$Key`" -o StrictHostKeyChecking=no $User@$IP -p $Port"
    } else {
        Write-Host "❌ 密钥文件不存在: $Key" -ForegroundColor Red
        return
    }
} else {
    $sshCommand = "ssh -o StrictHostKeyChecking=no $User@$IP -p $Port"
}

Write-Host "`n📝 连接命令: $sshCommand" -ForegroundColor Cyan

# 如果是上传或下载文件
if ($Upload -and $File) {
    if (-not $RemotePath) {
        $RemotePath = "/root"
    }
    Write-Host "📤 上传文件: $File -> $RemotePath" -ForegroundColor Yellow
    if ($Key) {
        scp -i "$Key" -P $Port $File $User@$IP`:$RemotePath
    } else {
        scp -P $Port $File $User@$IP`:$RemotePath
    }
    exit
}

if ($Download -and $File) {
    if (-not $RemotePath) {
        $RemotePath = "."
    }
    Write-Host "📥 下载文件: $File -> $RemotePath" -ForegroundColor Yellow
    if ($Key) {
        scp -i "$Key" -P $Port $User@$IP`:$File $RemotePath
    } else {
        scp -P $Port $User@$IP`:$File $RemotePath
    }
    exit
}

# 执行SSH连接
Write-Host "`n按回车开始连接..." -ForegroundColor Yellow
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

& powershell -Command $sshCommand

